﻿using System.Data.Common;
using System.Data.SqlServerCe;
using System.Windows;
using System.Windows.Data;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using System.ComponentModel;
using System;
using System.Data;
using System.Data.Objects;
using System.Xml.Linq;
using System.Configuration;
using Microsoft.Win32;
using System.Text;

namespace AppTrans
{
    public partial class MainWindow : Window
    {
        db_trans3Entities database;

        public int WorkMonth = 3;
        public int FinMonth = 4;
        public int FuelMonth = 4;

        public static string CheckAdminRole()
        {
            return (string)RegistryKeyValues.GetValue("role");
        }
        public string ShowMenu = CheckAdminRole();

        public MainWindow()
        {
            Write2File.Main("MainWindow: begin");

            InitializeComponent();
            InitializeData();
            InitializeReports();

            this.PreviewKeyDown += new KeyEventHandler(deleteRow_PreviewKeyDown);

            Write2File.Main("MainWindow: end");
        }

        private void InitializeData()
        {
            Write2File.Main("InitializeData: Поехали загружать данные...");

            database = new db_trans3Entities();
            MainPanel.DataContext = database;

            CheckVersionBD();

            if ((string)CheckAdminRole() == "admin")
            {
                InitializeDataWorks1(); //Работа - Продажа+Доставка
                InitializeDataWorks2(); //Работа - Перевозки
                InitializeDataWorks3(); //Работа - Продажа
                InitializeDataWorks4(); //Работа - Услуги
                InitializeDataWorks5(); //Работа - Закупка на склад
                InitializeDataWorks6(); //Работа - Продажа со склада
                InitializeDataWorks7(); //Работа - Ремонтные дни
                InitializeDataWorks8(); //Работа - Заявки на работы
                InitializeDataWorks9(); //Работа - Техн. режим
                InitializeDataTransactions(); //Финансовые транзакции
                InitializeDataRefuelings(); //Учет топлива
            }
            else 
            {
                InitializeDataWorks8(); //Работа - Заявки на работы
                InitializeDataWorks1(); //Работа - Продажа+Доставка
                InitializeDataWorks2(); //Работа - Перевозки
                InitializeDataWorks3(); //Работа - Продажа
                InitializeDataRefuelings(); //Учет топлива
            }
                VersionDBDataGrid.ItemsSource = from t in database.VersionDBs
                                                orderby t.Id
                                                select new
                                                {
                                                    Id = t.Id,
                                                    Версия = t.Version,
                                                    Дата_обновления = t.Data
                                                };
                ShowWhatsNew();
                ReportErrors();

                Write2File.Main("InitializeData - Завершено!");
        }

        private void InitializeDataWorks1()
        {
            Write2File.Main("InitializeDataWork1:begin - Начало загрузки данных для закладки Работа - Продажа+Доставка");

            //database = new db_trans3Entities();
            //MainPanel.DataContext = database;

            //int WorkMonth;
            //int FinMonth;
            //int FuelMonth;
            //GetSetCountMonth(out WorkMonth, out FinMonth, out FuelMonth);

            var firsDay = FirstDay.firsDay(WorkMonth);

            //Работа - Продажа+Доставка
            WorksDataGrid.ItemsSource = from w in database.Works
                                        where w.OperType == 1 && w.Date >= firsDay
                                        orderby w.Date
                                        select w;

            //Справочники для полей типа ComboBox таблицы Works 1 - Закладка "Продажа+Доставка"
            WorksOperTypeList.ItemsSource = from DictionaryOperTypes in database.DictionaryOperTypes
                                            where DictionaryOperTypes.Id == 1
                                            orderby DictionaryOperTypes.Id
                                            select new { DictionaryOperTypes.Id, DictionaryOperTypes.Name };

            WorksLoadingPlaceList.ItemsSource = from DictionaryPlaces in database.DictionaryPlaces
                                                where DictionaryPlaces.View == 1
                                                orderby DictionaryPlaces.Name
                                                select DictionaryPlaces;

            WorksUnloadingPlaceList.ItemsSource = from DictionaryPlaces in database.DictionaryPlaces
                                                  where DictionaryPlaces.View == 1
                                                  orderby DictionaryPlaces.Name
                                                  select DictionaryPlaces;

            WorksMachineList.ItemsSource = from DictionaryMachines in database.DictionaryMachines
                                           orderby DictionaryMachines.Name
                                           where DictionaryMachines.View == 1
                                           select DictionaryMachines;

            WorksDriverList.ItemsSource = from DictionaryDrivers in database.DictionaryDrivers
                                          orderby DictionaryDrivers.Name
                                          where DictionaryDrivers.View == 1
                                          select DictionaryDrivers;

            WorksGoodsList.ItemsSource = from DictionaryGoods in database.DictionaryGoods
                                         orderby DictionaryGoods.Name
                                         where DictionaryGoods.View == 1
                                         select DictionaryGoods;

            WorksSupplierList.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                            orderby DictionaryPartners.Name
                                            where DictionaryPartners.View == 1 || DictionaryPartners.Supplier == 1
                                            select DictionaryPartners;

            WorksCurrencyPurchasingList.ItemsSource = from DictionaryCurrencies in database.DictionaryCurrencies
                                                      orderby DictionaryCurrencies.Name
                                                      where DictionaryCurrencies.View == 1
                                                      select DictionaryCurrencies;

            WorksSupplierCommissionList.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                                      orderby DictionaryPartners.Name
                                                      where DictionaryPartners.View == 1 || DictionaryPartners.SupplierCommission == 1
                                                      select DictionaryPartners;

            WorksCustomerList.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                            orderby DictionaryPartners.Name
                                            where DictionaryPartners.View == 1 || DictionaryPartners.Customer == 1
                                            select DictionaryPartners;

            WorksCurrencySalesList.ItemsSource = from DictionaryCurrencies in database.DictionaryCurrencies
                                                 orderby DictionaryCurrencies.Name
                                                 where DictionaryCurrencies.View == 1
                                                 select DictionaryCurrencies;

            WorksCustomerCommissionList.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                                      orderby DictionaryPartners.Name
                                                      where DictionaryPartners.View == 1 || DictionaryPartners.CustomerCommission == 1
                                                      select DictionaryPartners;

            WorksProjectList.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                           orderby DictionaryProjects.Name
                                           where DictionaryProjects.View == 1
                                           select DictionaryProjects;

            Write2File.Main("InitializeDataWork1:end - Конец загрузки данных для закладки Работа - Продажа+Доставка");
        } //Работа - Продажа+Доставка

        private void InitializeDataWorks2()
        {
            Write2File.Main("InitializeDataWork2:begin - Начало загрузки данных для закладки Работа - Перевозки");

            //database = new db_trans3Entities();
            //MainPanel.DataContext = database;

            //int WorkMonth;
            //int FinMonth;
            //int FuelMonth;
            //GetSetCountMonth(out WorkMonth, out FinMonth, out FuelMonth);

            var firsDay = FirstDay.firsDay(WorkMonth);

            //Работа - Перевозки
            WorksDataGrid2.ItemsSource = from w2 in database.Works
                                         where w2.OperType == 2 && w2.Date >= firsDay
                                         orderby w2.Date
                                         select w2;

            //Справочники для полей типа ComboBox таблицы Works2 - Перевозки
            WorksOperTypeList2.ItemsSource = from DictionaryOperTypes2 in database.DictionaryOperTypes
                                             where DictionaryOperTypes2.Id == 2
                                             orderby DictionaryOperTypes2.Name
                                             select DictionaryOperTypes2;

            WorksLoadingPlaceList2.ItemsSource = from DictionaryPlaces2 in database.DictionaryPlaces
                                                 where DictionaryPlaces2.View == 1
                                                 orderby DictionaryPlaces2.Name
                                                 select DictionaryPlaces2;

            WorksUnloadingPlaceList2.ItemsSource = from DictionaryPlaces2 in database.DictionaryPlaces
                                                   where DictionaryPlaces2.View == 1
                                                   orderby DictionaryPlaces2.Name
                                                   select DictionaryPlaces2;

            WorksMachineList2.ItemsSource = from DictionaryMachines2 in database.DictionaryMachines
                                            orderby DictionaryMachines2.Name
                                            where DictionaryMachines2.View == 1
                                            select DictionaryMachines2;

            WorksDriverList2.ItemsSource = from DictionaryDrivers2 in database.DictionaryDrivers
                                           orderby DictionaryDrivers2.Name
                                           where DictionaryDrivers2.View == 1
                                           select DictionaryDrivers2;

            WorksGoodsList2.ItemsSource = from DictionaryGoods2 in database.DictionaryGoods
                                          orderby DictionaryGoods2.Name
                                          where DictionaryGoods2.View == 1
                                          select DictionaryGoods2;

            WorksCustomerList2.ItemsSource = from DictionaryPartners2 in database.DictionaryPartners
                                             orderby DictionaryPartners2.Name
                                             where DictionaryPartners2.View == 1 || DictionaryPartners2.Customer == 1
                                             select DictionaryPartners2;

            WorksCurrencySalesList2.ItemsSource = from DictionaryCurrencies2 in database.DictionaryCurrencies
                                                  orderby DictionaryCurrencies2.Name
                                                  where DictionaryCurrencies2.View == 1
                                                  select DictionaryCurrencies2;

            WorksCustomerCommissionList2.ItemsSource = from DictionaryPartners2 in database.DictionaryPartners
                                                       orderby DictionaryPartners2.Name
                                                       where DictionaryPartners2.View == 1 || DictionaryPartners2.CustomerCommission == 1
                                                       select DictionaryPartners2;

            WorksProjectList2.ItemsSource = from DictionaryProjects2 in database.DictionaryProjects
                                            orderby DictionaryProjects2.Name
                                            where DictionaryProjects2.View == 1
                                            select DictionaryProjects2;

            Write2File.Main("InitializeDataWork2:end - Конец загрузки данных для закладки Работа - Перевозки");
        } //Работа - Перевозки

        private void InitializeDataWorks3()
        {
            Write2File.Main("InitializeDataWork3:begin - Начало загрузки данных для закладки Работа - Продажа");

            //database = new db_trans3Entities();
            //MainPanel.DataContext = database;

            //int WorkMonth;
            //int FinMonth;
            //int FuelMonth;
            //GetSetCountMonth(out WorkMonth, out FinMonth, out FuelMonth);

            var firsDay = FirstDay.firsDay(WorkMonth);

            //Работа - Продажа
            WorksDataGrid3.ItemsSource = from w3 in database.Works
                                         where w3.OperType == 3 && w3.Date >= firsDay
                                         orderby w3.Date
                                         select w3;

            //Справочники для полей типа ComboBox таблицы Works3 - Закладка "Продажа"

            WorksOperTypeList3.ItemsSource = from DictionaryOperTypes3 in database.DictionaryOperTypes
                                             where DictionaryOperTypes3.Id == 3
                                             orderby DictionaryOperTypes3.Name
                                             select DictionaryOperTypes3;

            WorksGoodsList3.ItemsSource = from DictionaryGoods3 in database.DictionaryGoods
                                          orderby DictionaryGoods3.Name
                                          where DictionaryGoods3.View == 1
                                          select DictionaryGoods3;

            WorksSupplierList3.ItemsSource = from DictionaryPartners3 in database.DictionaryPartners
                                             orderby DictionaryPartners3.Name
                                             where DictionaryPartners3.View == 1 || DictionaryPartners3.Supplier == 1
                                             select DictionaryPartners3;

            WorksCurrencyPurchasingList3.ItemsSource = from DictionaryCurrencies3 in database.DictionaryCurrencies
                                                       orderby DictionaryCurrencies3.Name
                                                       where DictionaryCurrencies3.View == 1
                                                       select DictionaryCurrencies3;

            WorksSupplierCommissionList3.ItemsSource = from DictionaryPartners3 in database.DictionaryPartners
                                                       orderby DictionaryPartners3.Name
                                                       where DictionaryPartners3.View == 1 || DictionaryPartners3.SupplierCommission == 1
                                                       select DictionaryPartners3;

            WorksCustomerList3.ItemsSource = from DictionaryPartners3 in database.DictionaryPartners
                                             orderby DictionaryPartners3.Name
                                             where DictionaryPartners3.View == 1 || DictionaryPartners3.Customer == 1
                                             select DictionaryPartners3;

            WorksCurrencySalesList3.ItemsSource = from DictionaryCurrencies3 in database.DictionaryCurrencies
                                                  orderby DictionaryCurrencies3.Name
                                                  where DictionaryCurrencies3.View == 1
                                                  select DictionaryCurrencies3;

            WorksCustomerCommissionList3.ItemsSource = from DictionaryPartners3 in database.DictionaryPartners
                                                       orderby DictionaryPartners3.Name
                                                       where DictionaryPartners3.View == 1 || DictionaryPartners3.CustomerCommission == 1
                                                       select DictionaryPartners3;

            WorksProjectList3.ItemsSource = from DictionaryProjects3 in database.DictionaryProjects
                                            orderby DictionaryProjects3.Name
                                            where DictionaryProjects3.View == 1
                                            select DictionaryProjects3;

            Write2File.Main("InitializeDataWork3:end - Конец загрузки данных для закладки Работа - Продажа");
        } //Работа - Продажа

        private void InitializeDataWorks4()
        {
            Write2File.Main("InitializeDataWork4:begin - Начало загрузки данных для закладки Работа - Услуги");

            //database = new db_trans3Entities();
            //MainPanel.DataContext = database;
           
            //int WorkMonth;
            //int FinMonth;
            //int FuelMonth;
            //GetSetCountMonth(out WorkMonth, out FinMonth, out FuelMonth);

            var firsDay = FirstDay.firsDay(WorkMonth);

            //Работа - Услуги
            WorksDataGrid4.ItemsSource = from w4 in database.Works
                                         where w4.OperType == 4
                                         orderby w4.Date
                                         select w4;
            //Справочники для полей типа ComboBox таблицы Works4 - Услуги

            WorksOperTypeList4.ItemsSource = from DictionaryOperTypes4 in database.DictionaryOperTypes
                                             where DictionaryOperTypes4.Id == 4
                                             orderby DictionaryOperTypes4.Name
                                             select DictionaryOperTypes4;

            WorksCustomerList4.ItemsSource = from DictionaryPartners4 in database.DictionaryPartners
                                             orderby DictionaryPartners4.Name
                                             where DictionaryPartners4.View == 1 || DictionaryPartners4.Customer == 1
                                             select DictionaryPartners4;

            WorksCurrencySalesList4.ItemsSource = from DictionaryCurrencies4 in database.DictionaryCurrencies
                                                  orderby DictionaryCurrencies4.Name
                                                  where DictionaryCurrencies4.View == 1
                                                  select DictionaryCurrencies4;

            WorksCustomerCommissionList4.ItemsSource = from DictionaryPartners4 in database.DictionaryPartners
                                                       orderby DictionaryPartners4.Name
                                                       where DictionaryPartners4.View == 1 || DictionaryPartners4.CustomerCommission == 1
                                                       select DictionaryPartners4;

            WorksProjectList4.ItemsSource = from DictionaryProjects4 in database.DictionaryProjects
                                            orderby DictionaryProjects4.Name
                                            where DictionaryProjects4.View == 1
                                            select DictionaryProjects4;

            Write2File.Main("InitializeDataWork4:end - Конец загрузки данных для закладки Работа - Услуги");
        } //Работа - Услуги

        private void InitializeDataWorks5()
        {
            Write2File.Main("InitializeDataWork5:begin - Начало загрузки данных для закладки Работа - Закупка на склад");

            //database = new db_trans3Entities();
            //MainPanel.DataContext = database;

            //int WorkMonth;
            //int FinMonth;
            //int FuelMonth;
            //GetSetCountMonth(out WorkMonth, out FinMonth, out FuelMonth);

            var firsDay = FirstDay.firsDay(WorkMonth);

            //Работа - Закупка на склад
            WorksDataGrid5.ItemsSource = from w5 in database.Works
                                         where w5.OperType == 5 && w5.Date >= firsDay
                                         orderby w5.Date
                                         select w5;

            //Справочники для полей типа ComboBox таблицы Works 5 - Закладка "Закупка на склад"
            WorksOperTypeList5.ItemsSource = from DictionaryOperTypes5 in database.DictionaryOperTypes
                                             where DictionaryOperTypes5.Id == 5
                                             orderby DictionaryOperTypes5.Id
                                             select new { DictionaryOperTypes5.Id, DictionaryOperTypes5.Name };

            WorksLoadingPlaceList5.ItemsSource = from DictionaryPlaces5 in database.DictionaryPlaces
                                                 where DictionaryPlaces5.View == 1
                                                 orderby DictionaryPlaces5.Name
                                                 select DictionaryPlaces5;

            WorksUnloadingPlaceList5.ItemsSource = from DictionaryPlaces5 in database.DictionaryPlaces
                                                   where DictionaryPlaces5.View == 1 && DictionaryPlaces5.Store == 1
                                                   orderby DictionaryPlaces5.Name
                                                   select DictionaryPlaces5;

            WorksMachineList5.ItemsSource = from DictionaryMachines5 in database.DictionaryMachines
                                            orderby DictionaryMachines5.Name
                                            where DictionaryMachines5.View == 1
                                            select DictionaryMachines5;

            WorksDriverList5.ItemsSource = from DictionaryDrivers5 in database.DictionaryDrivers
                                           orderby DictionaryDrivers5.Name
                                           where DictionaryDrivers5.View == 1
                                           select DictionaryDrivers5;

            WorksGoodsList5.ItemsSource = from DictionaryGoods5 in database.DictionaryGoods
                                          orderby DictionaryGoods5.Name
                                          where DictionaryGoods5.View == 1
                                          select DictionaryGoods5;

            WorksSupplierList5.ItemsSource = from DictionaryPartners5 in database.DictionaryPartners
                                             orderby DictionaryPartners5.Name
                                             where DictionaryPartners5.View == 1 || DictionaryPartners5.Supplier == 1
                                             select DictionaryPartners5;

            WorksCurrencyPurchasingList5.ItemsSource = from DictionaryCurrencies5 in database.DictionaryCurrencies
                                                       orderby DictionaryCurrencies5.Name
                                                       where DictionaryCurrencies5.View == 1
                                                       select DictionaryCurrencies5;

            WorksSupplierCommissionList5.ItemsSource = from DictionaryPartners5 in database.DictionaryPartners
                                                       orderby DictionaryPartners5.Name
                                                       where DictionaryPartners5.View == 1 || DictionaryPartners5.SupplierCommission == 1
                                                       select DictionaryPartners5;

            WorksProjectList5.ItemsSource = from DictionaryProjects5 in database.DictionaryProjects
                                            orderby DictionaryProjects5.Name
                                            where DictionaryProjects5.View == 1
                                            select DictionaryProjects5;

            Write2File.Main("InitializeDataWork5:end - Конец загрузки данных для закладки Работа - Закупка на склад");
        } //Работа - Закупка на склад

        private void InitializeDataWorks6()
        {
            Write2File.Main("InitializeDataWork6:begin - Начало загрузки данных для закладки Работа - Продажа со склада");

            //database = new db_trans3Entities();
            //MainPanel.DataContext = database;

            //int WorkMonth;
            //int FinMonth;
            //int FuelMonth;
            //GetSetCountMonth(out WorkMonth, out FinMonth, out FuelMonth);

            var firsDay = FirstDay.firsDay(WorkMonth);

            //Работа - Продажа со склада
            WorksDataGrid6.ItemsSource = from w6 in database.Works
                                         where w6.OperType == 6 && w6.Date >= firsDay
                                         orderby w6.Date
                                         select w6;

            //Справочники для полей типа ComboBox таблицы Works 6 - Закладка "Продажа со склада"
            WorksOperTypeList6.ItemsSource = from DictionaryOperTypes6 in database.DictionaryOperTypes
                                             where DictionaryOperTypes6.Id == 6
                                             orderby DictionaryOperTypes6.Id
                                             select new { DictionaryOperTypes6.Id, DictionaryOperTypes6.Name };

            WorksLoadingPlaceList6.ItemsSource = from DictionaryPlaces6 in database.DictionaryPlaces
                                                 where DictionaryPlaces6.View == 1 && DictionaryPlaces6.Store == 1
                                                 orderby DictionaryPlaces6.Name
                                                 select DictionaryPlaces6;

            WorksUnloadingPlaceList6.ItemsSource = from DictionaryPlaces6 in database.DictionaryPlaces
                                                   where DictionaryPlaces6.View == 1
                                                   orderby DictionaryPlaces6.Name
                                                   select DictionaryPlaces6;

            WorksMachineList6.ItemsSource = from DictionaryMachines6 in database.DictionaryMachines
                                            orderby DictionaryMachines6.Name
                                            where DictionaryMachines6.View == 1
                                            select DictionaryMachines6;

            WorksDriverList6.ItemsSource = from DictionaryDrivers6 in database.DictionaryDrivers
                                           orderby DictionaryDrivers6.Name
                                           where DictionaryDrivers6.View == 1
                                           select DictionaryDrivers6;

            WorksGoodsList6.ItemsSource = from DictionaryGoods6 in database.DictionaryGoods
                                          orderby DictionaryGoods6.Name
                                          where DictionaryGoods6.View == 1
                                          select DictionaryGoods6;

            WorksCustomerList6.ItemsSource = from DictionaryPartners6 in database.DictionaryPartners
                                             orderby DictionaryPartners6.Name
                                             where DictionaryPartners6.View == 1 || DictionaryPartners6.Customer == 1
                                             select DictionaryPartners6;

            WorksCurrencySalesList6.ItemsSource = from DictionaryCurrencies6 in database.DictionaryCurrencies
                                                  orderby DictionaryCurrencies6.Name
                                                  where DictionaryCurrencies6.View == 1
                                                  select DictionaryCurrencies6;

            WorksCustomerCommissionList6.ItemsSource = from DictionaryPartners6 in database.DictionaryPartners
                                                       orderby DictionaryPartners6.Name
                                                       where DictionaryPartners6.View == 1 || DictionaryPartners6.CustomerCommission == 1
                                                       select DictionaryPartners6;

            WorksProjectList6.ItemsSource = from DictionaryProjects6 in database.DictionaryProjects
                                            orderby DictionaryProjects6.Name
                                            where DictionaryProjects6.View == 1
                                            select DictionaryProjects6;

            Write2File.Main("InitializeDataWork6:end - Конец загрузки данных для закладки Работа - Продажа со склада");
        } //Работа - Продажа со склада

        private void InitializeDataWorks7()
        {
            Write2File.Main("InitializeDataWork7:begin - Начало загрузки данных для закладки Работа - Ремонтные дни");

            //database = new db_trans3Entities();
            //MainPanel.DataContext = database;

            //Работа - Ремонтные дни
            WorksDataGrid7.ItemsSource = from w7 in database.Works
                                         where w7.OperType == 7
                                         orderby w7.Date
                                         select w7;

            //Справочники для полей типа ComboBox таблицы Works7 - Ремонтные дни
            WorksOperTypeList7.ItemsSource = from DictionaryOperTypes7 in database.DictionaryOperTypes
                                             where DictionaryOperTypes7.Id == 7
                                             orderby DictionaryOperTypes7.Name
                                             select DictionaryOperTypes7;

            WorksDriverList7.ItemsSource = from DictionaryDrivers7 in database.DictionaryDrivers
                                           orderby DictionaryDrivers7.Name
                                           where DictionaryDrivers7.View == 1
                                           select DictionaryDrivers7;

            WorksProjectList7.ItemsSource = from DictionaryProjects7 in database.DictionaryProjects
                                            orderby DictionaryProjects7.Name
                                            where DictionaryProjects7.View == 1
                                            select DictionaryProjects7;

            Write2File.Main("InitializeDataWork7:end - Конец загрузки данных для закладки Работа - Ремонтные дни");
        } //Работа - Ремонтные дни

        private void InitializeDataWorks8()
        {
            Write2File.Main("InitializeDataWork8:begin - Начало загрузки данных для закладки Работа - Заявки на работы");

            //database = new db_trans3Entities();
            //MainPanel.DataContext = database;

            //Работа - Заявки на работы
            WorksDataGrid8.ItemsSource = from w8 in database.Works
                                         where w8.OperType == 8
                                         orderby w8.Date
                                         select w8;

            //Справочники для полей типа ComboBox таблицы Works8 - Заявки
            WorksOperTypeList8.ItemsSource = from DictionaryOperTypes8 in database.DictionaryOperTypes
                                             where DictionaryOperTypes8.Id == 1 || DictionaryOperTypes8.Id == 2 ||
                                                   DictionaryOperTypes8.Id == 3 || DictionaryOperTypes8.Id == 5 ||
                                                   DictionaryOperTypes8.Id == 6 || DictionaryOperTypes8.Id == 8
                                             orderby DictionaryOperTypes8.Name
                                             select DictionaryOperTypes8;

            WorksLoadingPlaceList8.ItemsSource = from DictionaryPlaces8 in database.DictionaryPlaces
                                                 where DictionaryPlaces8.View == 1
                                                 orderby DictionaryPlaces8.Name
                                                 select DictionaryPlaces8;

            WorksUnloadingPlaceList8.ItemsSource = from DictionaryPlaces8 in database.DictionaryPlaces
                                                   where DictionaryPlaces8.View == 1
                                                   orderby DictionaryPlaces8.Name
                                                   select DictionaryPlaces8;

            WorksMachineList8.ItemsSource = from DictionaryMachines8 in database.DictionaryMachines
                                            orderby DictionaryMachines8.Name
                                            where DictionaryMachines8.View == 1
                                            select DictionaryMachines8;

            WorksDriverList8.ItemsSource = from DictionaryDrivers8 in database.DictionaryDrivers
                                           orderby DictionaryDrivers8.Name
                                           where DictionaryDrivers8.View == 1
                                           select DictionaryDrivers8;

            WorksGoodsList8.ItemsSource = from DictionaryGoods8 in database.DictionaryGoods
                                          orderby DictionaryGoods8.Name
                                          where DictionaryGoods8.View == 1
                                          select DictionaryGoods8;

            WorksCustomerList8.ItemsSource = from DictionaryPartners8 in database.DictionaryPartners
                                             orderby DictionaryPartners8.Name
                                             where DictionaryPartners8.View == 1 || DictionaryPartners8.Customer == 1
                                             select DictionaryPartners8;

            WorksProjectList8.ItemsSource = from DictionaryProjects8 in database.DictionaryProjects
                                            orderby DictionaryProjects8.Name
                                            where DictionaryProjects8.View == 1
                                            select DictionaryProjects8;
            
            Write2File.Main("InitializeDataWork8:end - Конец загрузки данных для закладки Работа - Заявки на работы");
        } //Работа - Заявки на работы

        private void InitializeDataWorks9()
        {
            Write2File.Main("InitializeDataWork9:begin - Начало загрузки данных для закладки Работа - Техн. режим");

            //database = new db_trans3Entities();
            //MainPanel.DataContext = database;

            //Работа - Техн. режим
            WorksDataGrid9.ItemsSource = from w9 in database.Works
                                         orderby w9.Date
                                         select w9;

            //Справочники для полей типа ComboBox таблицы Works - Закладка "Техн. режим
            WorksOperTypeList9.ItemsSource = from DictionaryOperTypes9 in database.DictionaryOperTypes
                                             orderby DictionaryOperTypes9.Name
                                             select DictionaryOperTypes9;

            WorksLoadingPlaceList9.ItemsSource = database.DictionaryPlaces; //Можно выбрать значение NULL в ComboBox

            WorksUnloadingPlaceList9.ItemsSource = database.DictionaryPlaces; //Можно выбрать значение NULL в ComboBox

            WorksMachineList9.ItemsSource = database.DictionaryMachines; //Можно выбрать значение NULL в ComboBox

            WorksDriverList9.ItemsSource = database.DictionaryDrivers;  //Можно выбрать значение NULL в ComboBox

            WorksGoodsList9.ItemsSource = database.DictionaryGoods;  //Можно выбрать значение NULL в ComboBox

            WorksSupplierList9.ItemsSource = database.DictionaryPartners; //Можно выбрать значение NULL в ComboBox

            WorksCurrencyPurchasingList9.ItemsSource = database.DictionaryCurrencies; //Можно выбрать значение NULL в ComboBox

            WorksSupplierCommissionList9.ItemsSource = database.DictionaryPartners; //Можно выбрать значение NULL в ComboBox

            WorksCustomerList9.ItemsSource = database.DictionaryPartners; //Можно выбрать значение NULL в ComboBox

            WorksCurrencySalesList9.ItemsSource = database.DictionaryCurrencies; //Можно выбрать значение NULL в ComboBox

            WorksCustomerCommissionList9.ItemsSource = database.DictionaryPartners; //Можно выбрать значение NULL в ComboBox

            WorksProjectList9.ItemsSource = from DictionaryProjects9 in database.DictionaryProjects
                                            orderby DictionaryProjects9.Name
                                            where DictionaryProjects9.View == 1
                                            select DictionaryProjects9;

            Write2File.Main("InitializeDataWork9:end - Конец загрузки данных для закладки Работа - Техн. режим");
        } //Работа - Техн. режим

        private void InitializeDataTransactions()
        {
            Write2File.Main("InitializeDataTransactions:begin - Начало загрузки данных по финансам");

            //database = new db_trans3Entities();
            //MainPanel.DataContext = database;

            //int WorkMonth;
            //int FinMonth;
            //int FuelMonth;
            //GetSetCountMonth(out WorkMonth, out FinMonth, out FuelMonth);

            var firsDay = FirstDay.firsDay(FinMonth);

            TransactionsDataGrid.ItemsSource = from t in database.Transactions
                                               where t.Date >= firsDay
                                               orderby t.Date
                                               select t;

            //Справочники для полей типа ComboBox таблицы Transactions - Закладка "Финансы"

            TransactionsTypeList.ItemsSource = from DictionaryTransactionTypes in database.DictionaryTransactionTypes
                                               orderby DictionaryTransactionTypes.Name
                                               select new
                                               {
                                                   Id = DictionaryTransactionTypes.Id,
                                                   Name = DictionaryTransactionTypes.Name
                                               };

            TransactionsCurrencyList.ItemsSource = from DictionaryCurrencies in database.DictionaryCurrencies
                                                   orderby DictionaryCurrencies.Name
                                                   where DictionaryCurrencies.View == 1
                                                   select new
                                                   {
                                                       Id = DictionaryCurrencies.Id,
                                                       ShortName = DictionaryCurrencies.ShortName
                                                   };

            TransactionsCategoryList.ItemsSource = from DictionaryCategories in database.DictionaryCategories
                                                   orderby DictionaryCategories.DictionaryTransactionType.Id
                                                   where DictionaryCategories.View == 1
                                                   select new
                                                   {
                                                       Id = DictionaryCategories.Id,
                                                       Name = DictionaryCategories.Name + " (" + DictionaryCategories.DictionaryTransactionType.Name + ")"
                                                   };

            TransactionsPartnerList.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                                  orderby DictionaryPartners.Name
                                                  where DictionaryPartners.View == 1 || DictionaryPartners.FinPartner == 1
                                                  select DictionaryPartners;

            TransactionsDriverList.ItemsSource = from DictionaryDrivers in database.DictionaryDrivers
                                                 orderby DictionaryDrivers.Name
                                                 where DictionaryDrivers.View == 1
                                                 select DictionaryDrivers;

            TransactionsProjectList.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                                  orderby DictionaryProjects.Name
                                                  where DictionaryProjects.View == 1
                                                  select DictionaryProjects;

            //Список типов транзакций для справочника категорий
            DictionaryCategoriesTypeList.ItemsSource = database.DictionaryTransactionTypes;

            Write2File.Main("InitializeDataTransactions:end - Конец загрузки данных по финансам");
        } //Финансовые транзакции

        private void InitializeDataRefuelings()
        {
            Write2File.Main("InitializeDataRefuelings:begin - Начало загрузки данных по учету топлива");

            //database = new db_trans3Entities();
            //MainPanel.DataContext = database;

            //int WorkMonth;
            //int FinMonth;
            //int FuelMonth;
            //GetSetCountMonth(out WorkMonth, out FinMonth, out FuelMonth);
            
            var firsDay = FirstDay.firsDay(FuelMonth);

            RefuelingDataGrid.ItemsSource = from r in database.Refuelings //Заправка своя АЗС
                                            where r.FuelOperType == 1 && r.Date >= firsDay
                                            orderby r.Date
                                            select r;

            RefuelingDataGrid2.ItemsSource = from r2 in database.Refuelings //Заправка у постащика
                                             where r2.FuelOperType == 2 && r2.Date >= firsDay
                                             orderby r2.Date
                                             select r2;

            //Справочники для полей типа ComboBox таблицы Refueling
            RefuelingFuelOperTypeList.ItemsSource = from DictionaryFuelOperTypes in database.DictionaryFuelOperTypes
                                                    where DictionaryFuelOperTypes.Id == 1
                                                    orderby DictionaryFuelOperTypes.Id
                                                    select new { DictionaryFuelOperTypes.Id, DictionaryFuelOperTypes.Name };

            RefuelingGasSattionsList.ItemsSource = from DictionaryGasStations in database.DictionaryGasStations
                                                   where DictionaryGasStations.View == 1
                                                   orderby DictionaryGasStations.Name
                                                   select new
                                                   {
                                                       Id = DictionaryGasStations.Id,
                                                       Name = DictionaryGasStations.Name
                                                   };

            RefuelingsMachineList.ItemsSource = from DictionaryMachines in database.DictionaryMachines
                                                orderby DictionaryMachines.Name
                                                where DictionaryMachines.View == 1
                                                select new
                                                {
                                                    Id = DictionaryMachines.Id,
                                                    Name = DictionaryMachines.Name
                                                };

            RefuelingDriverList.ItemsSource = from DictionaryDrivers in database.DictionaryDrivers
                                              orderby DictionaryDrivers.Name
                                              where DictionaryDrivers.View == 1
                                              select DictionaryDrivers;

            RefuelingsFuelList.ItemsSource = from DictionaryCategories in database.DictionaryCategories
                                             orderby DictionaryCategories.DictionaryTransactionType.Id
                                             where DictionaryCategories.View == 1 && DictionaryCategories.Fuel == 1
                                             select new
                                             {
                                                 Id = DictionaryCategories.Id,
                                                 Name = DictionaryCategories.Name
                                             };

            RefuelingsProjectList.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                                orderby DictionaryProjects.Name
                                                where DictionaryProjects.View == 1
                                                select new
                                                {
                                                    Id = DictionaryProjects.Id,
                                                    Name = DictionaryProjects.Name
                                                };

            //Справочники для полей типа ComboBox таблицы Refueling2 - заправка у поставщика
            RefuelingFuelOperTypeList2.ItemsSource = from DictionaryFuelOperTypes in database.DictionaryFuelOperTypes
                                                     where DictionaryFuelOperTypes.Id == 2
                                                     orderby DictionaryFuelOperTypes.Id
                                                     select new { DictionaryFuelOperTypes.Id, DictionaryFuelOperTypes.Name };

            RefuelingFuelSupplierList2.ItemsSource = from DictionaryPartners in database.DictionaryPartners
                                                     orderby DictionaryPartners.Name
                                                     where DictionaryPartners.View == 1 || DictionaryPartners.FuelSupplier == 1
                                                     select DictionaryPartners;

            RefuelingFuelTypeList2.ItemsSource = from DictionaryFuelType in database.DictionaryFuelTypes
                                                 where DictionaryFuelType.View == 1
                                                 orderby DictionaryFuelType.Name
                                                 select new
                                                 {
                                                     Id = DictionaryFuelType.Id,
                                                     Name = DictionaryFuelType.Name
                                                 };

            RefuelingsMachineList2.ItemsSource = from DictionaryMachines in database.DictionaryMachines
                                                 orderby DictionaryMachines.Name
                                                 where DictionaryMachines.View == 1
                                                 select new
                                                 {
                                                     Id = DictionaryMachines.Id,
                                                     Name = DictionaryMachines.Name
                                                 };

            RefuelingDriverList2.ItemsSource = from DictionaryDrivers in database.DictionaryDrivers
                                               orderby DictionaryDrivers.Name
                                               where DictionaryDrivers.View == 1
                                               select DictionaryDrivers;


            RefuelingsProjectList2.ItemsSource = from DictionaryProjects in database.DictionaryProjects
                                                 orderby DictionaryProjects.Name
                                                 where DictionaryProjects.View == 1
                                                 select new
                                                 {
                                                     Id = DictionaryProjects.Id,
                                                     Name = DictionaryProjects.Name
                                                 };

            Write2File.Main("InitializeDataRefuelings:end - Конец загрузки данных по учету топлива");
        } //Учет топлива

        private void InitializeReports()
        {
            Write2File.Main("InitializeReports: begin - начало построения отчетов и конструкторов");

            if ((string)CheckAdminRole() == "admin")
            {

                //database = new db_trans3Entities();
                //MainPanel.DataContext = database;

                //Параметры диапазона дат для конструктора
                DateTime varFinFromDate;
                DateTime varFinToDate;
                DateTime varWorkFromDate;
                DateTime varWorkToDate;
                GetSetDataRepConstructor(out varFinFromDate, out varFinToDate, out varWorkFromDate, out varWorkToDate);

                //CheckDateParam(varFinFromDate, varFinToDate, varWorkFromDate, varWorkToDate);

                Write2File.Main("Начало загрузки конструкторов");
                WorkReportConstructor(varWorkFromDate, varWorkToDate);
                Write2File.Main("Конструктор Работы - готов");
                FinanceReportConstructor(varFinFromDate, varFinToDate);
                Write2File.Main("Конструктор Финансы - готов");
                FuelConstructor(varFinFromDate, varFinToDate);
                Write2File.Main("Конструктор Топливо - готов");
                Write2File.Main("Конец загрузки конструкторов");

                Write2File.Main("Начало формирования отчетов - курим...");

                //Reports Kassa
                Kassa.ItemsSource = database.ExecuteStoreQuery<KassaObject>(KassaObject.sql);
                Write2File.Main("Отчет Kassa - готов");

                //Reports Store
                Store.ItemsSource = database.ExecuteStoreQuery<StoreObject>(StoreObject.sql);
                Write2File.Main("Отчет Store - готов");

                //Reports FuelSupplier - Расчеты с поставщиками топлива
                FuelSupplier.ItemsSource = database.ExecuteStoreQuery<FuelSupplierObject>(FuelSupplierObject.sql);
                Write2File.Main("Отчет FuelSupplier - готов");

                //Reports FuelMachinas2
                FuelMachinas2.ItemsSource = database.ExecuteStoreQuery<FuelMachinas2Object>(FuelMachinas2Object.sql);
                Write2File.Main("Отчет FuelMachinas2 - готов");

                //Reports FuelMachinas2_month
                FuelMachinas2_month.ItemsSource = database.ExecuteStoreQuery<FuelMachinas2_monthObject>(FuelMachinas2_monthObject.sql);
                Write2File.Main("Отчет FuelMachinas2_month - готов");

                //Reports FuelMonitoring
                FuelMonitoring.ItemsSource = database.ExecuteStoreQuery<FuelMonitoringObject>(FuelMonitoringObject.sql);
                Write2File.Main("Отчет FuelMonitoring - готов");

                //Reports FuelTotal
                FuelTotal.ItemsSource = database.ExecuteStoreQuery<FuelTotalObject>(FuelTotalObject.sql);
                Write2File.Main("Отчет FuelTotal - готов");

                //Reports FuelProjects
                FuelProjects.ItemsSource = database.ExecuteStoreQuery<FuelProjectsObject>(FuelProjectsObject.sql);
                Write2File.Main("Отчет FuelProjects - готов");

                //Reports FuelGasStations
                FuelGasStations.ItemsSource = database.ExecuteStoreQuery<FuelGasStationsObject>(FuelGasStationsObject.sql);
                Write2File.Main("Отчет FuelGasStations - готов");

                //Reports FuelMachinas
                FuelMachinas.ItemsSource = database.ExecuteStoreQuery<FuelMachinasObject>(FuelMachinasObject.sql);
                Write2File.Main("Отчет FuelMachinas - готов");

                //Reports Receivables
                Receivables.ItemsSource = database.ExecuteStoreQuery<ReceivablesObject>(ReceivablesObject.sql);
                Write2File.Main("Отчет Receivables - готов");

                //Reports Payables
                Payables.ItemsSource = database.ExecuteStoreQuery<PayablesObject>(PayablesObject.sql);
                Write2File.Main("Отчет Payables - готов");

                //Reports Categories
                ReportCategories.ItemsSource = database.ExecuteStoreQuery<ReportCategoriesObject>(ReportCategoriesObject.sql);
                Write2File.Main("Отчет Categories - готов");

                //Reports Procent
                ReportProcent.ItemsSource = database.ExecuteStoreQuery<ProcentObject>(ProcentObject.sql);
                Write2File.Main("Отчет Procent - готов");

                //Reports Nalog
                ReportNalog.ItemsSource = database.ExecuteStoreQuery<ReportNalogObject>(ReportNalogObject.sql);
                Write2File.Main("Отчет Nalog - готов");

                //Reports Dolg
                ReportDolg.ItemsSource = database.ExecuteStoreQuery<ReportDolgObject>(ReportDolgObject.sql);
                Write2File.Main("Отчет Dolg - готов");

                //Report Error
                ReportError.ItemsSource = database.ExecuteStoreQuery<ReportErrorObject>(ReportErrorObject.sql);
                Write2File.Main("Отчет Error - готов");

                //Reports Receivables NEW
                ReceivablesNew.ItemsSource = database.ExecuteStoreQuery<ReceivablesObjectNew>(ReceivablesObjectNew.sql);
                Write2File.Main("Отчет Receivables NEW - готов");

                //Reports Payables NEW
                PayablesNew.ItemsSource = database.ExecuteStoreQuery<PayablesObjectNew>(PayablesObjectNew.sql);
                Write2File.Main("Отчет Payables NEW - готов");

                //Reports Зарплата водителя
                ReportZPVoditel.ItemsSource = database.ExecuteStoreQuery<ReportZPVoditelObject>(ReportZPVoditelObject.sql);
                Write2File.Main("Отчет Зарплата водителя - готов");

                //Reports Комиссии
                ReportComission.ItemsSource = database.ExecuteStoreQuery<ReportComissionObject>(ReportComissionObject.sql);
                Write2File.Main("Отчет Комиссии - готов");

                Write2File.Main("InitializeReports: end - конец построения отчетов и конструкторов");
            }
            else
            {
                //Параметры диапазона дат для конструктора
                DateTime varFinFromDate;
                DateTime varFinToDate;
                DateTime varWorkFromDate;
                DateTime varWorkToDate;
                GetSetDataRepConstructor(out varFinFromDate, out varFinToDate, out varWorkFromDate, out varWorkToDate);
                
                Write2File.Main("Начало загрузки конструкторов");
                
                WorkReportConstructor(varWorkFromDate, varWorkToDate);
                Write2File.Main("Конструктор Работы - готов");
                FuelConstructor(varFinFromDate, varFinToDate);
                Write2File.Main("Конструктор Топливо - готов");

                Write2File.Main("Конец загрузки конструкторов");

                //Reports Receivables NEW
                ReceivablesNew.ItemsSource = database.ExecuteStoreQuery<ReceivablesObjectNew>(ReceivablesObjectNew.sql);
                Write2File.Main("Отчет Receivables NEW - готов");

                //Reports Payables NEW
                PayablesNew.ItemsSource = database.ExecuteStoreQuery<PayablesObjectNew>(PayablesObjectNew.sql);
                Write2File.Main("Отчет Payables NEW - готов");

                //Reports FuelSupplier - Расчеты с поставщиками топлива
                FuelSupplier.ItemsSource = database.ExecuteStoreQuery<FuelSupplierObject>(FuelSupplierObject.sql);
                Write2File.Main("Отчет FuelSupplier - готов");

                //Reports FuelMachinas2 - Расход топлива (всего)
                FuelMachinas2.ItemsSource = database.ExecuteStoreQuery<FuelMachinas2Object>(FuelMachinas2Object.sql);
                Write2File.Main("Отчет FuelMachinas2 - готов");

                //Reports FuelMachinas2_month - Расход топлава (месяц)
                FuelMachinas2_month.ItemsSource = database.ExecuteStoreQuery<FuelMachinas2_monthObject>(FuelMachinas2_monthObject.sql);
                Write2File.Main("Отчет FuelMachinas2_month - готов");

                //Reports FuelMonitoring - Мониторинг топлива
                FuelMonitoring.ItemsSource = database.ExecuteStoreQuery<FuelMonitoringObject>(FuelMonitoringObject.sql);
                Write2File.Main("Отчет FuelMonitoring - готов");

            }
        } //Построение отчетов

        // Получение диапазона дат для конструктора
        public void GetSetDataRepConstructor(out DateTime varFinFromDate, out DateTime varFinToDate, out DateTime varWorkFromDate, out DateTime varWorkToDate)
        {
            Write2File.Main("Получение диапазона дат для конструктора - начало");
            varFinFromDate = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_FinFromDate).First().FinFromDate;
            varFinToDate = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_FinToDate).First().FinToDate;
            varWorkFromDate = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_WorkFromDate).First().WorkFromDate;
            varWorkToDate = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_WorkToDate).First().WorkToDate;
            Write2File.Main("Получение диапазона дат для конструктора - конец");
        }

        // Получение кол-ва месяцув для построения дата гридов ввода информации
        //public void GetSetCountMonth(out int WorkMonth, out int FinMonth, out int FuelMonth)
        //{
        //    Write2File.Main("Выполнение SQL для получение кол-ва месяцув для дата гридов - начало");
            
        //    WorkMonth = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_select_set_WorkMonth).First().WorkMonth;
        //    FinMonth = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_select_set_FinMonth).First().FinMonth;
        //    FuelMonth = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_select_set_FuelMonth).First().FuelMonth;

        //    Write2File.Main("Выполнение SQL для получение кол-ва месяцув для дата гридов - конец");
        //}

        // Проверка версии БД и обновление
        
        public void CheckVersionBD()
        {
            Write2File.Main("CheckVersionBD - Проверка версии БД и обновление - начало");
            var resultCheckingTableVersionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_CheckingTableVersionDB).First().CheckingTableVersionDB;
            if (resultCheckingTableVersionDB == 0)
            {
                //Вывод сообщения про отсутствие таблицы VersionDB
                resultCheckingTableVersionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_CheckingTableVersionDB).First().CheckingTableVersionDB;
            }
            if (resultCheckingTableVersionDB == 1)
            {
                var versionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
                if (versionDB == 00)
                {
                    MessageBox.Show("Сейчас будет выполнено обновление БД до верcии 10");
                    new vbs_close().RunScript(Properties.Resources.AppTransBackup);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_insert_set1);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_insert_set2);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_insert_set3);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_insert_set4);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_InsertVersion10);
                    versionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
                    InitializeData();
                    InstructionCommandBinding_Executed(null, null);
                }
                //if (versionDB == 10)
                //{
                //    //MessageBox.Show("Сейчас будет выполнено обновление БД до версии 20./nСделайте резервную копию!");
                //    new vbs_close().RunScript(Properties.Resources.AppTransBackup);
                //};
                if (versionDB == 10)
                {
                    //MessageBox.Show("Сейчас будет выполнено обновление БД до версии 20. /n Сделайте резервную копию!");
                    //Запуск vbs скрsипта для резервного копирования БД
                    //new vbs_close().RunScript(Properties.Resources.AppTransBackup);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_1);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_2);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_3);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_4);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_5);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_6);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_7);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_8);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_9);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_10);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_11);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_12);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_13);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_14);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_15);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_16);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_17);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_18);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_19);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_20);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_21);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_22);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_23);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_24);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_25);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_26);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_27);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_28);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_29);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_30);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_31);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v20_32);
                    versionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
                    InitializeData();
                    InstructionCommandBinding_Executed(null, null);
                }
                if (versionDB == 20)
                {
                    //MessageBox.Show("Сейчас будет выполнено обновление БД до версии 30. /n Сделайте резервную копию!");
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_1);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_2);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_3);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_4);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_5);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_6);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_7);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_8);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_9);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_10);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_11);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_12);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_13);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_14);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_15);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_16);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v30_17);

                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_1);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_2);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_3);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_4);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v35_5);

                    versionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
                    InitializeData();
                    InstructionCommandBinding_Executed(null, null);
                }
                if (versionDB == 35)
                {
                    //MessageBox.Show("Сейчас будет выполнено обновление БД до версии 36. /n Сделайте резервную копию!");
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v36_1);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v36_2);

                    versionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
                    InitializeData();
                    InstructionCommandBinding_Executed(null, null);
                }
                if (versionDB == 36)
                {
                    //MessageBox.Show("Сейчас будет выполнено обновление БД до версии 37. /n Сделайте резервную копию!");
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v37_1);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v37_2);

                    versionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
                    InitializeData();
                    InstructionCommandBinding_Executed(null, null);
                }
                if (versionDB == 37)
                {
                    //MessageBox.Show("Сейчас будет выполнено обновление БД до версии 38. /n Сделайте резервную копию!");
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v38_1);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_db_for_v38_2);

                    versionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
                    InitializeData();
                    InstructionCommandBinding_Executed(null, null);
                }
                if (versionDB == 38)
                {
                    //MessageBox.Show("Сейчас будет выполнено обновление БД до версии 38. /n Сделайте резервную копию!");
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_insert_set_WorkMonth);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_insert_set_FinMonth);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_insert_set_FuelMonth);
                    database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_update_ver_db);

                    versionDB = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
                    InitializeData();
                    InstructionCommandBinding_Executed(null, null);
                }
            }
            Write2File.Main("CheckVersionBD - Проверка версии БД и обновление - конец");
        }

        // Подготовка данных для конструктора "Работы"
        private void WorkReportConstructor(DateTime? fromDate = null, DateTime? toDate = null)
        {
            if (fromDate == null) fromDate = DateTime.MinValue;
            if (toDate == null) toDate = DateTime.MaxValue;
            WorksRep.ItemsSource = from work in database.Works
                                   where work.Date >= fromDate &&
                                         work.Date <= toDate
                                   orderby work.Date
                                   select new
                                   {
                                       Дата = work.Date,
                                       Месяц = work.Date.Month,
                                       Год = work.Date.Year,
                                       ТипРаб = work.DictionaryOperType.Name,
                                       МестоЗагр = work.DictionaryPlace.Name,
                                       МестоРазгр = work.DictionaryPlace1.Name,
                                       Машина = work.DictionaryMachine.Name,
                                       Водитель = work.DictionaryDriver.Name,
                                       ЗарплВодит = work.SalaryDriver,
                                       Груз = work.DictionaryGood.Name,
                                       ВесЗагр = work.WeightDownload,
                                       ВесРазгр = work.Weight,
                                       Км = work.Distance,
                                       КолРаб = work.CountWork,
                                       Поставщик = work.DictionaryPartner2.Name, //Всегда проверять номер связи в db_trans3.edmx
                                       СуммаЗакупки = work.PriceOfPurchasing,
                                       ВалютаЗакупки = work.DictionaryCurrency.ShortName, //Всегда проверять номер связи в db_trans3.edmx
                                       КомиссионерПоставщика = work.DictionaryPartner3.Name, //Всегда проверять номер связи в db_trans3.edmx
                                       СуммаКомисПоставщика = work.PriceCommissionPurchase,
                                       Заказчик = work.DictionaryPartner.Name, //Всегда проверять номер связи в db_trans3.edmx
                                       СуммаПродажи = work.PriceOfSales,
                                       ВалютаПродажи = work.DictionaryCurrency1.ShortName,
                                       КомиссионерЗаказч = work.DictionaryPartner1,
                                       СуммаКомисЗаказч = work.PriceCommissionSales,
                                       Проект = work.DictionaryProject.Name,
                                       Примечание = work.Discription
                                   };
                                //WorksRepNew.ItemsSource = from work in database.Works
                                //                          where work.Date >= fromDate &&
                                //                                work.Date <= toDate
                                //                          orderby work.Date
                                //                          select new
                                //                          {
                                //                              Дата = work.Date,
                                //                              Месяц = work.Date.Month,
                                //                              Год = work.Date.Year,
                                //                              ТипРаб = work.DictionaryOperType.Name,
                                //                              МестоЗагр = work.DictionaryPlace.Name,
                                //                              МестоРазгр = work.DictionaryPlace1.Name,
                                //                              Машина = work.DictionaryMachine.Name,
                                //                              Водитель = work.DictionaryDriver.Name,
                                //                              ЗарплВодит = work.SalaryDriver,
                                //                              ИтогЗарплВодит = work.SalaryDriver * work.CountWork,
                                //                              Груз = work.DictionaryGood.Name,
                                //                              Вес = work.Weight,
                                //                              ИтогВес = work.Weight * work.CountWork,
                                //                              Км = work.Distance,
                                //                              ИтогКм = work.Distance * work.CountWork,
                                //                              КолРаб = work.CountWork,
                                //                              Поставщик = work.DictionaryPartner.Name,
                                //                              СуммаЗакупки = work.PriceOfPurchasing,
                                //                              ИтогСуммаЗакупки = work.PriceOfPurchasing * work.CountWork,
                                //                              ВалютаЗакупки = work.DictionaryCurrency.ShortName,
                                //                              КомиссионерПоставщика = work.DictionaryPartner1.Name,
                                //                              СуммаКомисПоставщика = work.PriceCommissionPurchase,
                                //                              ИтогСуммаКомисПоставщика = work.PriceCommissionPurchase * work.CountWork,
                                //                              Заказчик = work.DictionaryPartner2.Name,
                                //                              СуммаПродажи = work.PriceOfSales,
                                //                              ИтогСуммаПрод = work.PriceOfSales * work.CountWork,
                                //                              ВалютаПродажи = work.DictionaryCurrency1.ShortName,
                                //                              КомиссионерЗаказч = work.DictionaryPartner3,
                                //                              СуммаКомисЗаказч = work.PriceCommissionSales,
                                //                              ИтогСуммаКомисЗаказч = work.PriceCommissionSales * work.CountWork,
                                //                              Проект = work.DictionaryProject.Name,
                                //                              Описание = work.Discription
                                //                          };
        }

        // Подготовка данных для конструктора "Финансы"
        private void FinanceReportConstructor(DateTime? fromDate = null, DateTime? toDate = null)
            {
                if (fromDate == null) fromDate = DateTime.MinValue;
                if (toDate == null) toDate = DateTime.MaxValue;
                FinRep.ItemsSource = from Transactions in database.Transactions
                                     where Transactions.Date >= fromDate &&
                                           Transactions.Date <= toDate
                                     orderby Transactions.Date
                                     select new
                                     {
                                         Дата = Transactions.Date,
                                         Месяц = Transactions.Date.Month,
                                         Год = Transactions.Date.Year,
                                         Тип = Transactions.DictionaryTransactionType.Name,
                                         Сумма = Transactions.Summa,
                                         Валюта = Transactions.DictionaryCurrency.ShortName,
                                         Категория = Transactions.DictionaryCategory.Name,
                                         Партнер = Transactions.DictionaryPartner.Name,
                                         Водитель = Transactions.DictionaryDriver.Name,
                                         Литры = Transactions.Liters,
                                         Проект = Transactions.DictionaryProject.Name,
                                         Примечание = Transactions.Discription
                                     };
            }

        // Подготовка данных для конструктора "Учет топлива"
        private void FuelConstructor(DateTime? fromDate = null, DateTime? toDate = null)
        {
                if (fromDate == null) fromDate = DateTime.MinValue;
                if (toDate == null) toDate = DateTime.MaxValue;
                FuelRep.ItemsSource = from Refuelings in database.Refuelings
                                      where Refuelings.Date >= fromDate &&
                                            Refuelings.Date <= toDate
                                      orderby Refuelings.Date
                                      select new
                                      {
                                          Дата = Refuelings.Date,
                                          Месяц = Refuelings.Date.Month,
                                          Год = Refuelings.Date.Year,
                                          ВидЗаправки = Refuelings.DictionaryFuelOperType.Name,
                                          Партнер = Refuelings.DictionaryPartner.Name,
                                          ТопливоСправочн = Refuelings.DictionaryFuelType.Name,
                                          Машина = Refuelings.DictionaryMachine.Name,
                                          Водитель = Refuelings.DictionaryDriver.Name,
                                          Литры = Refuelings.Liters,
                                          Сумма = Refuelings.Price,
                                          ОстатокВбаке = Refuelings.FuelRemaining,
                                          ПробегGPS = Refuelings.Distance,
                                          Одометр = Refuelings.Odometer,
                                          ТопливоКатегор = Refuelings.DictionaryCategory.Name,
                                          АЗС_Карта = Refuelings.DictionaryGasStation.Name,
                                          Проект = Refuelings.DictionaryProject.Name,
                                          Примечание = Refuelings.Discription
                                      };
        }

        // Уведомление про найденные ошибки
        private void ReportErrors()
        {
            Write2File.Main("ReportErrors - начало");
            ReportError.ItemsSource = database.ExecuteStoreQuery<ReportErrorObject>(ReportErrorObject.sql);
            var reportErrors = database.ExecuteStoreQuery<ReportErrorObject>(ReportErrorObject.sql);
            var i = 0;
            foreach (var reportError in reportErrors)
            {
                var errorsCountString = reportError.Кол_во_ошибок;
                var levelErrorsString = reportError.Уровень_ошибки;
                var errorsCount = 0;
                int.TryParse(errorsCountString, out errorsCount);

                if (errorsCount > 0 && levelErrorsString == "Критичный")
                {
                    i += errorsCount;
                }
            }
            if (i > 0)
            {
                MessageBox.Show("Найдены критические ошибки.\nПроверьте отчет Настройки --> Ошибки!\nКол-во критических ошибок = " + i, "Внимание, найдены ошибки!", MessageBoxButton.OK, MessageBoxImage.Warning);
            }
            Write2File.Main("ReportErrors - конец");
        }

        // Окно с проверкой на ошибки
        private void CheckErrors()
        {
            Write2File.Main("CheckErrors - начало");
            ReportError.ItemsSource = database.ExecuteStoreQuery<ReportErrorObject>(ReportErrorObject.sql);
            var reportErrors = database.ExecuteStoreQuery<ReportErrorObject>(ReportErrorObject.sql);
                int critical = 0;
                int warning = 0;
                int info = 0;
            foreach (var reportError in reportErrors)
            {
                var errorsCountString = reportError.Кол_во_ошибок;
                var levelErrorsString = reportError.Уровень_ошибки;
                var errorsCount = 0;

                int.TryParse(errorsCountString, out errorsCount);

                if (errorsCount > 0 && levelErrorsString == "Критичный")
                {
                    critical += errorsCount;
                }
                if (errorsCount > 0 && levelErrorsString == "Предупреждение")
                {
                    warning += errorsCount;
                }
                if (errorsCount > 0 && levelErrorsString == "Информационный")
                {
                    info += errorsCount;
                }
            }                
            MessageBox.Show("Кол-во критических ошибок = " + critical + "\nКол-во предупреждений = " + warning + "\nКол-во информационных сообщений = " + info, "Проверка на ошибки", MessageBoxButton.OK, MessageBoxImage.Warning);
            Write2File.Main("CheckErrors - конец");
        }

        // Открытие окна что нового при старте
        private void ShowWhatsNew()
        {
            //Проверка флага ShowWhatsNew
            var ShowWhatsNew = RegistryKeyValues.GetValue("ShowWhatsNew");
  
            if ((string)ShowWhatsNew == null)
            {
                RegistryKeyValues.SetValue("ShowWhatsNew", "0");
            }

            if ((string)ShowWhatsNew == "0")
            {
                //MessageBox.Show("ShowWhatsNew == 1");
                InstructionCommandBinding_Executed(null, null);
                RegistryKeyValues.SetValue("ShowWhatsNew", "1");
            }
        }

        #region Events

        // Проверка - Были ли изменения в базе. <returns>true, если база изменена</returns>
        private bool isDatabaseDirty()
        {
            return database.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified).Any();
        }

        private bool TryToSave()
        {
            Write2File.Main("TryToSave - начало");
            try
            {
                database.SaveChanges();
            }
            catch (Exception exc)
            {
                StatusBarText.Text = "Ошибка при сохранении в " + DateTime.Now.TimeOfDay;
                MessageBox.Show(exc.InnerException.Message, "Ошибка при сохранении", MessageBoxButton.OK, MessageBoxImage.Error);
                return false;
            }
            Write2File.Main("TryToSave - конец");
            return true;
        }

        //Подтверждение при выходе (Сохранить - Да/Нет)
        private bool SaveDataConfirm()
        {
            /// Изменений в базе не было, значит не нужно запрашивать сохранение
            if (!isDatabaseDirty())
                return true;

            if (MessageBox.Show("Сохранить все изменения?", "Выход", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
                return TryToSave();

            return true;
        }

        void exitCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            var success = SaveDataConfirm();
            if (!success)
                e.Cancel = true;
            new vbs_close().RunScript(Properties.Resources.AppTransBackup);
        }

        void saveCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (TryToSave())
            {
                InitializeData();
                StatusBarText.Text = "Сохранено в " + DateTime.Now.TimeOfDay;
            }
        }

        void deleteRow_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Device.Target.GetType().Name == "DataGridCell")
            {
                if (e.Key == Key.Delete)
                {
                    MessageBoxResult res = MessageBox.Show("Вы хотите удалить запись?", "Удаление", MessageBoxButton.YesNo, MessageBoxImage.Question);
                    e.Handled = (res == MessageBoxResult.No);
                    
                    if (res == MessageBoxResult.Yes)
                    {
                        MessageBoxResult res1 = MessageBox.Show("Уверены что необходимо удалить!?", "Подтверждение удаления", MessageBoxButton.YesNo, MessageBoxImage.Warning);
                        e.Handled = (res1 == MessageBoxResult.No);
                    }
                }
            }
        }

        void CheckErrors_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            CheckErrors();
        }

        void CheckDateParam_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            DateTime varFinFromDate;
            DateTime varFinToDate;
            DateTime varWorkFromDate;
            DateTime varWorkToDate;
            GetSetDataRepConstructor(out varFinFromDate, out varFinToDate, out varWorkFromDate, out varWorkToDate);
            MessageBox.Show("WorkDateFrom =" + varWorkFromDate + "\nWorkDateTo =" + varWorkToDate + "\nFinDateFrom =" + varFinFromDate + "\nFinDateTo =" + varFinToDate);
        }

        void BackupDB_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            new vbs_close().RunScript(Properties.Resources.AppTransBackup);
        }

        void DebugMode_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            new DebugMode().RunScript(Properties.Resources.DebugMode);
        }

        void RunSQL_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            byte EnableRunSQL = byte.MinValue;
            EnableRunSQL = byte.Parse(ConfigurationManager.AppSettings["EnableRunSQL"]);
            if (EnableRunSQL == 1)
            {
                ConfigurationManager.AppSettings["EnableRunSQL"] = "2";
                MessageBoxResult show = MessageBox.Show("Значение EnableRunSQL = " + EnableRunSQL);
            }
            if (EnableRunSQL == 2)
            {
                MessageBoxResult show = MessageBox.Show("Значение EnableRunSQL = " + EnableRunSQL);
            }
            else
            {
                MessageBoxResult show = MessageBox.Show("Некорректное значение параметра. \nEnableRunSQL = " + EnableRunSQL);
            }
        }

        void VerDB_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            var resultCheckingTableVersionDB2 = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_CheckingTableVersionDB).First().CheckingTableVersionDB;
            var versionDB2 = database.ExecuteStoreQuery<RunSQLObject>(RunSQLObject.sql_MaxVersionDB).First().MaxVersionDB;
            MessageBox.Show("Наличие таблицы VersionDB: " + resultCheckingTableVersionDB2 +
            "\nТекущая версия БД: " + versionDB2 +
            "\nВход в систему: " + RegistryKeyValues.GetValue("LastStartProgram") +
            "\nDebug mode: " + RegistryKeyValues.GetValue("debug_mode"), "Версия БД");
        }

        void refreshCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            Write2File.Main("\nrefresh - начало");
            if (isDatabaseDirty())
            {
                MessageBox.Show("База не сохранена. \rОтчеты могут быть не корректными", "Обновление отчетов");
            }
            //InitializeData();
            InitializeReports();
            StatusBarText.Text = "Cформированы отчеты из базы в " + DateTime.Now.TimeOfDay;
            Write2File.Main("refresh - конец");
        }

        #region Show windows //about, hotkeys, what's new

        void aboutCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            AboutWindow aboutWindow = new AboutWindow();
            aboutWindow.Show();
        }

        void HotkeysCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            HotkeysWindow HotkeysWindow = new HotkeysWindow();
            HotkeysWindow.Show();
        }

        void InstructionCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            InstructionWindow InstructionWindow = new InstructionWindow();
            InstructionWindow.Show();
        }

        #endregion

        // Клонирование строки - Работы 1 - Продажа+Доставка. Эту операцию можно выполнять только на сохраненной базе.
        private void WorksCloneButton_Click(object sender, RoutedEventArgs e)
        {
            Write2File.Main("Клонирование строки (Продажа+Доставка) - начало");
            if (isDatabaseDirty())
            {
                MessageBox.Show("Сохраните базу перед продолжением", "Clone", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                return;
            }

            Work work = WorksDataGrid.SelectedItem as Work;
            if (work == null)
                return;

            database.Detach(work);
            database.Works.AddObject(work);

            work.Date = DateTime.Now;
            work.WeightDownload = 0.01;
            work.Weight = 0.01;
            work.PriceOfPurchasing = 1;
            work.PriceOfSales = 1;
            work.Discription = null;

            TryToSave();
            InitializeDataWorks1();

            StatusBarText.Text = "Копирование и сохранение - выполнено в " + DateTime.Now.TimeOfDay;
            Write2File.Main("Клонирование строки (Продажа+Доставка) - конец");
        }

        // Клонирование строки - Работы 2 - Перевозки. Эту операцию можно выполнять только на сохраненной базе.
        private void WorksCloneButton_Click2(object sender, RoutedEventArgs e)
        {
            Write2File.Main("Клонирование строки (Перевозки) - начало");
            if (isDatabaseDirty())
            {
                MessageBox.Show("Сохраните базу перед продолжением", "Clone", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                return;
            }

            Work work = WorksDataGrid2.SelectedItem as Work;
            if (work == null)
                return;

            database.Detach(work);
            database.Works.AddObject(work);

            work.Date = DateTime.Now;
            work.WeightDownload = 0.01;
            work.Weight = 0.01;
            work.PriceOfSales = 1;
            work.Discription = null;

            TryToSave();
            InitializeDataWorks2();

            StatusBarText.Text = "Копирование и сохранение - выполнено в " + DateTime.Now.TimeOfDay;
            Write2File.Main("Клонирование строки (Перевозки) - конец");
        }

        // Клонирование строки - Работы 3 - Продажи. Эту операцию можно выполнять только на сохраненной базе.
        private void WorksCloneButton_Click3(object sender, RoutedEventArgs e)
        {
            Write2File.Main("Клонирование строки (Продажи) - начало");
            if (isDatabaseDirty())
            {
                MessageBox.Show("Сохраните базу перед продолжением", "Clone", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                return;
            }

            Work work = WorksDataGrid3.SelectedItem as Work;
            if (work == null)
                return;

            database.Detach(work);
            database.Works.AddObject(work);

            work.Date = DateTime.Now;
            work.WeightDownload = 0.01;
            work.Weight = 0.01;
            work.PriceOfPurchasing = 1;
            work.PriceOfSales = 1;
            work.Discription = null;

            TryToSave();
            InitializeDataWorks3();

            StatusBarText.Text = "Копирование и сохранение - выполнено в " + DateTime.Now.TimeOfDay;
            Write2File.Main("Клонирование строки (Продажи) - конец");
        }

        // Клонирование строки - Работы 5 - Закупка на склад. Эту операцию можно выполнять только на сохраненной базе.
        private void WorksCloneButton_Click5(object sender, RoutedEventArgs e)
        {
            Write2File.Main("Клонирование строки (Закупка на склад) - начало");

            if (isDatabaseDirty())
            {
                MessageBox.Show("Сохраните базу перед продолжением", "Clone", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                return;
            }

            Work work = WorksDataGrid5.SelectedItem as Work;
            if (work == null)
                return;

            database.Detach(work);
            database.Works.AddObject(work);

            work.Date = DateTime.Now;
            work.WeightDownload = 0.01;
            work.Weight = 0.01;
            work.PriceOfPurchasing = 1;
            work.Discription = null;

            TryToSave();
            InitializeDataWorks5();

            StatusBarText.Text = "Копирование и сохранение - выполнено в " + DateTime.Now.TimeOfDay;
            Write2File.Main("Клонирование строки (Закупка на склад) - конец");
        }

        // Клонирование строки - Работы 6 - Продажа со склада. Эту операцию можно выполнять только на сохраненной базе.
        private void WorksCloneButton_Click6(object sender, RoutedEventArgs e)
        {
            Write2File.Main("Клонирование строки (Продажа со склада) - начало");
            if (isDatabaseDirty())
            {
                MessageBox.Show("Сохраните базу перед продолжением", "Clone", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                return;
            }

            Work work = WorksDataGrid6.SelectedItem as Work;
            if (work == null)
                return;

            database.Detach(work);
            database.Works.AddObject(work);

            work.Date = DateTime.Now;
            work.WeightDownload = 0.01;
            work.Weight = 0.01;
            work.PriceOfSales = 1;
            work.Discription = null;

            TryToSave();
            InitializeDataWorks6();

            StatusBarText.Text = "Копирование и сохранение - выполнено в " + DateTime.Now.TimeOfDay;
            Write2File.Main("Клонирование строки (Продажа со склада) - конец");
        }

        // Клонирование строки - Работы 8 - Заявки. Эту операцию можно выполнять только на сохраненной базе.
        private void WorksCloneButton_Click8(object sender, RoutedEventArgs e)
        {
            Write2File.Main("Клонирование строки (Заявки) - начало");
            if (isDatabaseDirty())
            {
                MessageBox.Show("Сохраните базу перед продолжением", "Clone", MessageBoxButton.OK, MessageBoxImage.Asterisk);
                return;
            }

            Work work = WorksDataGrid8.SelectedItem as Work;
            if (work == null)
                return;

            database.Detach(work);
            database.Works.AddObject(work);

            work.Date = DateTime.Now;
            work.WeightDownload = 0.01;
            work.Weight = 0.01;
            work.PriceOfSales = 1;
            work.Discription = null;

            TryToSave();
            InitializeDataWorks8();

            StatusBarText.Text = "Копирование и сохранение - выполнено в " + DateTime.Now.TimeOfDay;

            Write2File.Main("Клонирование строки (Заявки) - конец");
        }

        #endregion

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
